<template>
  <div class="prescription-view">
    <div class="page-title">处方管理</div>
    
    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select v-model="status" placeholder="处方状态">
            <el-option label="全部" value="" />
            <el-option label="已开具" value="issued" />
            <el-option label="已发药" value="dispensed" />
            <el-option label="已作废" value="cancelled" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="department" placeholder="开具科室">
            <el-option label="全部" value="" />
            <el-option label="内科" value="internal" />
            <el-option label="外科" value="surgery" />
            <el-option label="儿科" value="pediatrics" />
            <el-option label="妇产科" value="obstetrics" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="选择日期范围"
          />
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchKey" placeholder="搜索患者姓名/处方编号" />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button @click="resetFilter">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 处方列表 -->
    <el-card class="prescription-list-card">
      <el-table
        :data="prescriptionList"
        border
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="patientName" label="患者姓名" />
        <el-table-column prop="patientId" label="患者ID" width="120" />
        <el-table-column prop="prescriptionNo" label="处方编号" />
        <el-table-column prop="department" label="开具科室" />
        <el-table-column prop="createTime" label="开具日期" />
        <el-table-column prop="medicineCount" label="药品数量" width="100" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'issued' ? 'info' : 
                     scope.row.status === 'dispensed' ? 'success' : 'danger'"
            >
              {{ scope.row.status === 'issued' ? '已开具' : 
                 scope.row.status === 'dispensed' ? '已发药' : '已作废' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleViewDetails(scope.row)"
            >
              查看详情
            </el-button>
            <el-button 
              size="small" 
              type="text" 
              text-color="#ff4d4f"
              @click="handleCancelPrescription(scope.row)"
              :disabled="scope.row.status !== 'issued'"
            >
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>

    <!-- 处方详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="处方详情"
      :width="800"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <div class="detail-header">
              <div class="hospital-name">XX医院处方单</div>
              <div class="prescription-no">处方编号：{{ currentPrescription.prescriptionNo || '-' }}</div>
            </div>
            
            <div class="patient-info">
              <div class="info-item">
                <span class="info-label">患者姓名：</span>
                <span class="info-value">{{ currentPrescription.patientName || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">性别：</span>
                <span class="info-value">{{ currentPrescription.gender || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">年龄：</span>
                <span class="info-value">{{ currentPrescription.age || '-' }}岁</span>
              </div>
              <div class="info-item">
                <span class="info-label">患者ID：</span>
                <span class="info-value">{{ currentPrescription.patientId || '-' }}</span>
              </div>
            </div>
            
            <div class="prescription-info">
              <div class="info-item">
                <span class="info-label">开具科室：</span>
                <span class="info-value">{{ currentPrescription.department || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">开具医生：</span>
                <span class="info-value">{{ currentPrescription.doctorName || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">开具日期：</span>
                <span class="info-value">{{ currentPrescription.createTime || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">处方状态：</span>
                <span class="info-value">
                  <el-tag
                    :type="currentPrescription.status === 'issued' ? 'info' : 
                           currentPrescription.status === 'dispensed' ? 'success' : 'danger'"
                  >
                    {{ currentPrescription.status === 'issued' ? '已开具' : 
                       currentPrescription.status === 'dispensed' ? '已发药' : '已作废' }}
                  </el-tag>
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="24">
          <el-card>
            <div slot="header">药品明细</div>
            <el-table
              :data="currentPrescription.medicines || []"
              border
              style="width: 100%"
            >
              <el-table-column prop="id" label="序号" width="80" />
              <el-table-column prop="name" label="药品名称" />
              <el-table-column prop="specification" label="规格" />
              <el-table-column prop="dosage" label="剂量" />
              <el-table-column prop="frequency" label="频次" />
              <el-table-column prop="days" label="天数" width="80" />
              <el-table-column prop="usage" label="用法" />
              <el-table-column prop="quantity" label="数量" width="80" />
              <el-table-column prop="unit" label="单位" width="80" />
            </el-table>
          </el-card>
        </el-col>
        
        <el-col :span="24">
          <el-card>
            <div slot="header">用药指导</div>
            <div class="instruction-content">
              {{ currentPrescription.instructions || '无特殊用药指导' }}
            </div>
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="handleDispenseMedicine"
          v-if="currentPrescription.status === 'issued'"
        >
          标记为已发药
        </el-button>
      </template>
    </el-dialog>

    <!-- 作废确认对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="作废处方"
      :width="400"
    >
      <div class="cancel-confirm">
        <p>确定要作废处方 <span class="prescription-no-highlight">{{ currentPrescription.prescriptionNo }}</span> 吗？</p>
        <p class="warning-text">提示：处方作废后将无法恢复，请谨慎操作。</p>
        <el-form-item label="作废原因：" required>
          <el-input 
            v-model="cancelReason" 
            type="textarea" 
            rows="3" 
            placeholder="请输入作废原因..." 
          />
        </el-form-item>
      </div>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" text-color="#fff" background="#ff4d4f" @click="confirmCancel">确认作废</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';

// 状态管理
const status = ref('');
const department = ref('');
const dateRange = ref([]);
const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(86);

// 对话框状态
const detailDialogVisible = ref(false);
const cancelDialogVisible = ref(false);
const currentPrescription = ref({});
const cancelReason = ref('');

// 模拟处方数据
const prescriptionList = ref([
  {
    id: 1,
    patientName: '张三',
    gender: '男',
    age: 35,
    patientId: 'PT20230512001',
    prescriptionNo: 'RX20230512001',
    department: '内科',
    doctorName: '张医生',
    createTime: '2023-05-12 09:30',
    medicineCount: 3,
    status: 'issued',
    instructions: '1. 阿司匹林肠溶片：饭后服用；2. 盐酸氨溴索口服溶液：摇匀后服用；3. 如有不适请及时就医。',
    medicines: [
      { id: 1, name: '阿司匹林肠溶片', specification: '100mg', dosage: '1片', frequency: '每日3次', days: 3, usage: '口服', quantity: 9, unit: '片' },
      { id: 2, name: '盐酸氨溴索口服溶液', specification: '100ml', dosage: '10ml', frequency: '每日3次', days: 3, usage: '口服', quantity: 1, unit: '瓶' },
      { id: 3, name: '复方甘草片', specification: '100片/瓶', dosage: '2片', frequency: '每日3次', days: 3, usage: '口服', quantity: 18, unit: '片' }
    ]
  },
  {
    id: 2,
    patientName: '李四',
    gender: '女',
    age: 28,
    patientId: 'PT20230512002',
    prescriptionNo: 'RX20230512002',
    department: '内科',
    doctorName: '张医生',
    createTime: '2023-05-12 10:15',
    medicineCount: 2,
    status: 'dispensed',
    dispenseTime: '2023-05-12 11:30',
    instructions: '1. 布洛芬缓释胶囊：饭后服用，避免空腹；2. 多饮温水。',
    medicines: [
      { id: 1, name: '布洛芬缓释胶囊', specification: '0.3g', dosage: '1粒', frequency: '每日2次', days: 3, usage: '口服', quantity: 6, unit: '粒' },
      { id: 2, name: '口服补液盐III', specification: '5.125g/袋', dosage: '1袋', frequency: '每日3次', days: 2, usage: '冲服', quantity: 6, unit: '袋' }
    ]
  },
  {
    id: 3,
    patientName: '王五',
    gender: '男',
    age: 45,
    patientId: 'PT20230511005',
    prescriptionNo: 'RX20230511005',
    department: '内科',
    doctorName: '李医生',
    createTime: '2023-05-11 15:40',
    medicineCount: 1,
    status: 'issued',
    instructions: '1. 每日固定时间服用；2. 定期监测血压变化；3. 不可自行停药。',
    medicines: [
      { id: 1, name: '硝苯地平控释片', specification: '30mg', dosage: '1片', frequency: '每日1次', days: 14, usage: '口服', quantity: 14, unit: '片' }
    ]
  },
  {
    id: 4,
    patientName: '赵六',
    gender: '女',
    age: 52,
    patientId: 'PT20230510012',
    prescriptionNo: 'RX20230510012',
    department: '外科',
    doctorName: '王医生',
    createTime: '2023-05-10 11:20',
    medicineCount: 2,
    status: 'cancelled',
    cancelTime: '2023-05-10 14:30',
    cancelReason: '患者对青霉素类药物过敏',
    instructions: '1. 术后抗感染治疗；2. 饭后服用。',
    medicines: [
      { id: 1, name: '阿莫西林胶囊', specification: '0.5g', dosage: '1粒', frequency: '每日3次', days: 7, usage: '口服', quantity: 21, unit: '粒' },
      { id: 2, name: '对乙酰氨基酚片', specification: '500mg', dosage: '1片', frequency: '必要时', days: 3, usage: '口服', quantity: 6, unit: '片' }
    ]
  },
  {
    id: 5,
    patientName: '钱七',
    gender: '男',
    age: 18,
    patientId: 'PT20230512008',
    prescriptionNo: 'RX20230512008',
    department: '内科',
    doctorName: '张医生',
    createTime: '2023-05-12 14:10',
    medicineCount: 2,
    status: 'issued',
    instructions: '1. 板蓝根颗粒：温水冲服；2. 注意休息，多饮水。',
    medicines: [
      { id: 1, name: '板蓝根颗粒', specification: '10g/袋', dosage: '1袋', frequency: '每日3次', days: 3, usage: '冲服', quantity: 9, unit: '袋' },
      { id: 2, name: '维生素C片', specification: '100mg', dosage: '1片', frequency: '每日3次', days: 5, usage: '口服', quantity: 15, unit: '片' }
    ]
  }
]);

// 搜索方法
const handleSearch = () => {
  console.log('搜索条件:', { 
    status: status.value,
    department: department.value,
    dateRange: dateRange.value, 
    searchKey: searchKey.value 
  });
  currentPage.value = 1;
  // 实际应用中这里会调用API进行搜索
};

// 重置筛选条件
const resetFilter = () => {
  status.value = '';
  department.value = '';
  dateRange.value = [];
  searchKey.value = '';
  currentPage.value = 1;
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 行点击事件
const handleRowClick = (row) => {
  handleViewDetails(row);
};

// 查看详情
const handleViewDetails = (row) => {
  // 查找完整处方信息（包含药品明细）
  const fullPrescription = prescriptionList.value.find(item => item.id === row.id);
  currentPrescription.value = { ...fullPrescription };
  detailDialogVisible.value = true;
};

// 处理作废操作
const handleCancelPrescription = (row) => {
  currentPrescription.value = { ...row };
  cancelReason.value = '';
  cancelDialogVisible.value = true;
};

// 确认作废
const confirmCancel = () => {
  if (!cancelReason.value.trim()) {
    // 可添加提示：请输入作废原因
    return;
  }
  
  // 模拟API请求
  axios.post(`/api/prescriptions/${currentPrescription.value.id}/cancel`, {
    reason: cancelReason.value
  }).then(response => {
    console.log('处方作废成功', response.data);
    // 更新列表中的数据
    const index = prescriptionList.value.findIndex(item => item.id === currentPrescription.value.id);
    if (index !== -1) {
      prescriptionList.value[index].status = 'cancelled';
      prescriptionList.value[index].cancelReason = cancelReason.value;
      prescriptionList.value[index].cancelTime = new Date().toLocaleString();
    }
    cancelDialogVisible.value = false;
  }).catch(error => {
    console.error('处方作废失败', error);
  });
};

// 标记为已发药
const handleDispenseMedicine = () => {
  // 模拟API请求
  axios.post(`/api/prescriptions/${currentPrescription.value.id}/dispense`, {
    dispenseTime: new Date().toLocaleString()
  }).then(response => {
    console.log('处方标记为已发药', response.data);
    // 更新列表中的数据
    const index = prescriptionList.value.findIndex(item => item.id === currentPrescription.value.id);
    if (index !== -1) {
      prescriptionList.value[index].status = 'dispensed';
      prescriptionList.value[index].dispenseTime = new Date().toLocaleString();
    }
    currentPrescription.value.status = 'dispensed';
    currentPrescription.value.dispenseTime = new Date().toLocaleString();
  }).catch(error => {
    console.error('操作失败', error);
  });
};
</script>

<style scoped>
.prescription-view {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #1e293b;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.prescription-list-card {
  padding: 0;
}

.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 0 15px 15px;
}

/* 详情对话框样式 */
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.hospital-name {
  font-size: 18px;
  font-weight: bold;
  color: #1e293b;
}

.prescription-no {
  color: #64748b;
  font-size: 14px;
}

.patient-info, .prescription-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 30px;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  color: #64748b;
  width: 100px;
}

.info-value {
  flex-grow: 1;
  font-weight: 500;
}

.instruction-content {
  padding: 10px;
  background-color: #f8fafc;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-line;
}

/* 作废对话框样式 */
.cancel-confirm {
  padding: 10px 0;
}

.prescription-no-highlight {
  color: #3b82f6;
  font-weight: 500;
}

.warning-text {
  color: #ff4d4f;
  margin-top: 10px;
  font-size: 14px;
}
</style>
    